//package com.xufeng.demo.test;
//
//import com.baomidou.mybatisplus.core.mapper.BaseMapper;
//import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
//import org.springframework.stereotype.Component;
//import org.springframework.transaction.support.TransactionTemplate;
//
//import java.util.ArrayList;
//import java.util.List;
//import java.util.concurrent.CompletableFuture;
//import java.util.function.Consumer;
//
///**
// * @author ASUS
// */
//@Component
//public class BatchInsertService<T> {
//
//    private static final int PAGE_SIZE = 1000;
//
//    private final ThreadPoolTaskExecutor executor;
//
//    public BatchInsertService( ThreadPoolTaskExecutor executor) {
//        this.executor = executor;
//    }
//
//    public void batchInsert(List<T> list, Consumer consumer) {
//        List<List<T>> userPages = splitList(list, PAGE_SIZE);
//        List<CompletableFuture<Void>> futures = new ArrayList<>();
//        for (int i = 0; i < userPages.size(); i++) {
//            List<T> page = userPages.get(i);
//            int index = i;
//            CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
//                try {
//                    TransactionTemplate transactionTemplate = new TransactionTemplate();
//                    transactionTemplate.executeWithoutResult(status -> {
//                        userMapper.insertBatch(page);
//                    });
//                } catch (Exception e) {
//                    throw new RuntimeException("Failed to insert users in page " + index, e);
//                }
//            }, executor);
//            futures.add(future);
//        }
//
//        for (int i = 0; i < orderPages.size(); i++) {
//            List<Order> page = orderPages.get(i);
//            int index = i;
//            CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
//                try {
//                    TransactionTemplate transactionTemplate = new TransactionTemplate();
//                    transactionTemplate.executeWithoutResult(status -> orderMapper.insertBatch(page));
//                } catch (Exception e) {
//                    throw new RuntimeException("Failed to insert orders in page " + index, e);
//                }
//            }, executor);
//            futures.add(future);
//        }
//
//        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
//    }
//
//    private <T> List<List<T>> splitList(List<T> list, int pageSize) {
//        List<List<T>> pages = new ArrayList<>();
//        int size = list.size();
//        int pageCount = (size + pageSize - 1) / pageSize;
//        for (int i = 0; i < pageCount; i++) {
//            int fromIndex = i * pageSize;
//            int toIndex = Math.min((i + 1) * pageSize, size);
//            List<T> page = list.subList(fromIndex, toIndex);
//            pages.add(page);
//        }
//        return pages;
//    }
//}
